<template>
    <div>
      <div style="margin: 10px 0">
        <el-input style="width: 200px" placeholder="请输入内容" suffix-icon="el-icon-search" v-model="name"></el-input>
        <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </div>
  
      <div style="margin: 10px 0">
        <!-- <el-button type="primary" @click="handleAdd">提交反馈</el-button> -->
      </div>
  
      <el-table :data="tableData"  :header-cell-class-name="'headerBg'"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- <el-table-column prop="id" label="ID" width="80" sortable></el-table-column> -->
        <el-table-column label="相关截图" align="center">
          <template slot-scope="scope">
            <el-carousel height="70px" v-if="scope.row.img" width="100">
              <el-carousel-item v-for="item in scope.row.img.split(',')" :key="item">
                <img v-if="item" height="70" width="70" :src="'http://101.43.223.224:8765/image/getImageById?id=' + item" />
              </el-carousel-item>
              </el-carousel>
            <el-tag v-else type="info">暂无数据</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="反馈内容" align="center"></el-table-column>
        <el-table-column prop="user" label="反馈人" align="center"></el-table-column>
        <el-table-column prop="email" label="联系方式" align="center"></el-table-column>
        <el-table-column prop="time" label="反馈时间" align="center"></el-table-column>
        <el-table-column prop="state" label="反馈状态" align="center">
          <template slot-scope="scope">
            {{ scope.row.state == 0 ? "待审核":scope.row.state == 1?"审核通过":scope.row.state == 2?"审核不通过" : "未知状态" }} 
          </template>
        </el-table-column>
        <el-table-column label="审核" v-if="user.role === 'ROLE_ADMIN'" width="203px" align="center">
          <template v-slot="scope">
            <el-button type="success" @click="changeState(scope.row, '1')" :disabled="scope.row.state !== '0'">审核通过</el-button>
            <el-button type="warning" @click="changeState2(scope.row, '2')" :disabled="scope.row.state !== '0'">审核不通过</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作"  width="200" align="center">
          <template slot-scope="scope" v-if="scope.row.user === user.username || user.role === 'ROLE_ADMIN'">
            <!-- <el-button type="text" v-if="scope.row.state != '0'" @click="handelAddhf">回复反馈<i class="el-icon-edit-outline"></i></el-button> -->
            <!-- <el-button type="text" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button> -->
            <el-popconfirm
                class="ml-5"
                confirm-button-text='确定'
                cancel-button-text='我再想想'
                icon="el-icon-info"
                icon-color="red"
                title="您确定删除吗？"
                @confirm="del(scope.row.id)"
            >
              <el-button type="text" slot="reference"><i class="el-icon-remove-outline"></i> 删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 10px 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <el-dialog title="反馈信息" :visible.sync="dialogFormVisible" width="30%">
        <el-form label-width="80px" size="small" ref="form" :model="form" :rules="form" :inline="true">
          <el-input v-model="form.id" placeholder="id" type="hidden"></el-input>

          <el-form-item label="头像">
            <el-upload style=" margin-left: 19%" action="123123123" list-type="picture-card" class="upload-demo" :show-file-list="false" :before-upload="beforeAvatarUpload">
              <img height="148" v-if="img" :src="img" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item><br>
          <el-form-item label="联系方式">
          <el-input v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="反馈内容">
            <el-input
                style="width: 400px;"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入内容"
                v-model="form.name">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="save">确 定</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 回复反馈 -->
      <el-dialog title="回复反馈" :visible.sync="dialogFormVisiblehf" width="60%">
        <el-form label-width="80px" size="small" ref="form" :model="form" :rules="form" :inline="true">
          <el-input v-model="form.id" placeholder="id" type="hidden"></el-input>

          <el-form-item label="标题">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="内容">
            <mavon-editor ref="md" v-model="form.content" :ishljs="true" @imgAdd="imgAdd" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="savehf">确 定</el-button>
          <el-button @click="dialogFormVisiblehf = false">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog title="回复反馈" :visible.sync="viewDialogVis" width="60%">
        <el-card>
          <div>
            <mavon-editor 
            class="md"
            :value="content"
            :subfield="false"
            :defaultOpen="'preview'"
            :toolbarsFlag="false"
            :editable="false"
            :scrollStyle="true"
            :ishljs="true"
            />
          </div>
        </el-card>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  export default {
    name: "Goods",
    data() {
      return {
        tableData: [],
        total: 0,
        pageNum: 1,
        pageSize: 10,
        name: "",
        form: {},
        // 图片回显
        img: "",
        //添加时赋值
        Urlavatar: "",
        value: true,
        content: '',
        dialogFormVisible: false, 
        dialogFormVisiblehf: false, 
        viewDialogVis: false, 
        multipleSelection: [],
        user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {} //获取当前登录用户信息
      }
    },
    created() {
      this.load()
    },
    methods: {
        //查看回复
      view(content) {
          this.content = content
          this.viewDialogVis = true
        },
        //绑定@imgAdd event
        imgAdd(pos, $file) {
          let $vm = this.$refs.md;
          
          // 第一步：将图片上传服务器
          const formData = new FormData();
          formData.append('file', $file);
          
          axios({
            url: 'http://127.0.0.1:16000/ImageFile/addImageFile1',
            method: 'post',
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data' }
          })
            .then((res) => {
              // 第二步：确保 res.data 包含正确的图片 ID
              const imageId ='http://101.43.223.224:8765/image/getImageById?id='+res.data;
              
              // 构建图片的URL
              const imageUrl = imageId;
              console.log($file); 
              
              // 第三步：调用 $img2Url 函数，将服务器端的图片地址替换到编辑器中

              $vm.$img2Url(pos, imageId);
              console.log(imageUrl); 
              
            })
            .catch((error) => {
              // Handle errors
              console.error('Error uploading image:', error);
            });
        },
      changeState(row, state) {
        this.form = JSON.parse(JSON.stringify(row))
        this.form.state = state;
        this.save();
      },
      changeState2(row, state) {
        this.form = JSON.parse(JSON.stringify(row))
        this.form.state = state;
        this.Fail();
      },
      load() {this.request.get("/feedback/page", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            name: this.name,
          }
        }).then(res => {
          this.tableData = res.data.records
          this.total = res.data.total
          
        })
      },
      // 文件上传校验
  beforeAvatarUpload(file) {
      //上传图片格式
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是JPG/PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB!");
        return false;
      }
      //赋值
      this.Urlavatar = file;
      this.img = URL.createObjectURL(file);
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false;
    },
      save(){
        this.$axios.post("/feedback/save",this.form).then(res => {
        if(res){
          this.$message.success("保存成功")
          this.img = ""
          this.dialogFormVisible = false
          this.load()
        }else{
          this.$message.error("保存失败")
       }
      })
  },
  Fail(){
        this.$axios.post("/feedback/Fail",this.form).then(res => {
        if(res){
          this.$message.success("保存成功")
          this.img = ""
          this.dialogFormVisible = false
          this.load()
        }else{
          this.$message.error("保存失败")
       }
      })
  },
  savehf(){
    this.request({method: "post",url: "/article/save",
        data:{
          "id": this.form.id,
          "name": this.form.name,
          "content": this.form.content,
          "user": this.form.user,
          "time": this.form.time,
        },
        //请求头
        headers: { 'Content-Type': 'application/json' },
      }).then(res => {
        if(res){
          this.$message.success("回复成功")
          this.dialogFormVisiblehf = false
          this.load()
        }else{
          this.$message.error("回复失败")
       }
      })
  },
  handelAddhf(){
    this.dialogFormVisiblehf = true
    this.form = {}
  },
      handleAdd() {
        this.dialogFormVisible = true
        this.form = {}
        this.$nextTick(() => {
          if(this.$refs.img) {
             this.$refs.img.clearFiles();
           }
           if(this.$refs.file) {
            this.$refs.file.clearFiles();
           }
        })
      },
      handleEdit(row) {
        this.form = JSON.parse(JSON.stringify(row))
        this.dialogFormVisible = true
         this.$nextTick(() => {
           if(this.$refs.img) {
             this.$refs.img.clearFiles();
           }
           if(this.$refs.file) {
            this.$refs.file.clearFiles();
           }
         })
      },
      del(id) {
        this.request.delete("/feedback/" + id).then(res => {
          if (res.code === '200') {
            this.$message.success("删除成功")
            this.load()
          } else {
            this.$message.error("删除失败")
          }
        })
      },
      handleSelectionChange(val) {
        console.log(val)
        this.multipleSelection = val
      },
      reset() {
        this.name = ""
        this.load()
      },
      handleSizeChange(pageSize) {
        console.log(pageSize)
        this.pageSize = pageSize
        this.load()
      },
      handleCurrentChange(pageNum) {
        console.log(pageNum)
        this.pageNum = pageNum
        this.load()
      },
      handleFileUploadSuccess(res) {
        this.form.file = res
      },
      handleImgUploadSuccess(res) {
        this.form.img = res
      },
      download(url) {
        window.open(url)
      },
    }
  }
  </script>
  
  
  <style>
  .headerBg {
    background: #eee!important;
  }
  </style>